const baseUrl = `${window.location.origin}/`;
var pointItems = [];
var i = 0;
var pointListData;
var a = 0;
var deletePointId = [];
var b = 0;
var editIndex = 0;
var index;
layui.use(['element','form','table','layer','laydate'], function () {
    var table = layui.table;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var form = layui.form;
    $ = layui.jquery;

    //执行一个laydate实例
    laydate.render({
        elem: '#firstInspectTime' //指定元素
        ,type: 'time'
    });

    table.render({
        elem: '#pointList'
        ,data: pointItems
        ,cellMinWidth: 80
        ,method: 'post'
        ,title: '点位表'
        ,page: true
        ,cols: [[
            {type:'numbers',title:'序号'}
            ,{field:'pointName', title:'点位名称'}
            // ,{field:'pointInspectTime', title:'巡查时长(min)'}
            // ,{field:'pointInspectErrorTime', title:'误差时长(min)'}
            ,{field:'right', title:'操作',templet:
                    function (data) {
                        return '<a class="layui-btn layui-btn-xs" lay-event="deletePoint">移除</a>'
                    }}
        ]]
        ,done:function (res,curr,count) {
            pointListData = res;
        }
    });

    table.render({
        elem: '#lineTable'
        ,cellMinWidth: 80
        ,method: 'post'
        ,url: baseUrl+'/eleinspect/line/getLineTable'
        ,title: '路线管理表'
        ,page: true
        ,cols: [[
            {type: 'checkbox', fixed: 'left'}
            ,{type:'numbers',title:'序号'}
            ,{field:'lineId',title:'线路编号', align:'center'}
            ,{field:'lineName', title:'线路名称', align:'center'}
            ,{field:'linePointNumber', title:'点位数量', align:'center'}
            ,{field:'lineInspectTime', title:'巡检总时长', align:'center',templet:
                function (d) {
                    if(!d.lineInspectTime){return '-'}
                    return d.lineInspectTime + '分钟';
                }}
            ,{field:'lineInspectErrorTime', title:'误差时长', align:'center',templet:
                    function (d) {
                        if(!d.lineInspectErrorTime){return '-'}
                        return d.lineInspectErrorTime + '分钟';
                    }}
            ,{field:'lineCreateTime', title:'创建时间', align:'center'}
            ,{field:'right', title:'操作', align:'center',templet:
                function (data) {
                    return '<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a><a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="detail">查看</a><a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>'
                }}
        ]]
    });

    table.render({
        elem: '#pointTable'
        ,cellMinWidth: 80
        ,method: 'post'
        ,url: baseUrl+'/eleinspect/line/getPointTable'
        ,title: '点位管理表'
        // ,page: true
        ,cols: [[
            {type: 'checkbox', fixed: 'left'}
            ,{type:'numbers',title:'序号'}
            ,{field:'pointName', title:'点位名称'}
            // ,{field:'pointInspectTime', title:'巡查时长(min)'}
            // ,{field:'pointInspectErrorTime', title:'误差时长(min)'}
            ]]
    });


    table.on('tool(lineTable)',function (obj) {
        var rowData = obj.data;
        if (obj.event === 'edit') {
            //初始化
            pointItems = [];
            i = 0;

            $("#toAddPoint").css('display','');
            $("#addBtn").css('display','');
            $.ajax({
                url: "/eleinspect/line/getLinePointInfo",
                type: 'post',
                data: {
                    mappingLineId: rowData.lineId
                },
                success:function(res){
                    for (i = 0;i < res.data.length;i++) {
                        // pointItems[i] = res.data[i];
                        pointItems.push(res.data[i]);
                    }
                    table.reload('pointList',{
                        data: res.data
                    },'data')
                }
            });

            deletePointId = [];
            b = 0;
            editIndex = 1;
            $("#lineId").val(rowData.lineId);
            $("#lineName").val(rowData.lineName);
            $("#lineInspectTime").val(rowData.lineInspectTime);
            $("#lineInspectErrorTime").val(rowData.lineInspectErrorTime);
            layer.open({
                type: 1,
                title:"编辑",
                offset: 'auto',
                skin:'demo-class',
                closeBtn: 1,
                shift: 2,
                area: ['80%', '100%'],
                shadeClose: true,
                content: $("#line_main"),
                skin: 'to-fix-select'
            });
        }else if(obj.event === 'detail'){
            $.ajax({
                url: baseUrl+"/eleinspect/line/getLinePointInfo",
                type: 'post',
                data: {
                    mappingLineId: rowData.lineId
                },
                success:function(res){
                    table.reload('pointList',{
                        data: res.data
                    },'data')
                }
            });

            deletePointId = [];
            b = 0;
            editIndex = 1;
            $("#lineId").val(rowData.lineId);
            $("#lineName").val(rowData.lineName);
            $("#lineInspectTime").val(rowData.lineInspectTime);
            $("#lineInspectErrorTime").val(rowData.lineInspectErrorTime);
            $("#toAddPoint").css('display','none');
            $("#addBtn").css('display','none');
            layer.open({
                type: 1,
                title:"查看",
                offset: 'auto',
                skin:'demo-class',
                closeBtn: 1,
                shift: 2,
                area: ['80%', '100%'],
                shadeClose: true,
                content: $("#line_main"),
                skin: 'to-fix-select'
            });
        }else if(obj.event === 'delete'){
            layer.confirm('确定删除?',{btn:['确定','返回']},function (index) {
                $.ajax({
                    url: baseUrl+"/eleinspect/line/deleteLine",
                    type:'post',
                    data:{
                        lineId:rowData.lineId
                    },
                    success:function(data){
                        if (data.code == 0) {
                            layer.msg(data.msg,{icon:1});
                        }else{
                            layer.msg("删除失败",{icon:2});
                        }
                        table.reload("lineTable",{});
                    }
                });
            });
        }
    });

    $('#toAdd').on('click',function () {
        //初始化
        $("#toAddPoint").css('display','');
        $("#addBtn").css('display','');
        $("#lineId").val("");
        $("#lineName").val("");
        $("#lineInspectTime").val("");
        $("#lineInspectErrorTime").val("");
        form.render();
        pointItems = [];
        i = 0;
        deletePointId = [];
        b = 0;
        editIndex = 0;
        table.reload('pointList',{
            data: pointItems
        },'data');

        layer.open({
            type: 1,
            title:"新增",
            offset: 'auto',
            skin:'demo-class',
            closeBtn: 1,
            shift: 2,
            area: ['80%', '100%'],
            shadeClose: true,
            content: $("#line_main"),
            skin: 'to-fix-select',
        });
    });

    $("#toAddPoint").on('click',function () {
        //初始化
        // pointItems = [];
        i = 0;
        a = 0;
        table.reload('pointTable', {});
        index = layer.open({
            type: 1,
            title:"增加点位",
            offset: 'auto',
            skin:'demo-class',
            closeBtn: 1,
            shift: 2,
            area: ['60%', '80%'],
            shadeClose: true,
            content: $("#point_main"),
            skin: 'to-fix-select',
        });
    });

    function hasTheData(data,id){
        if(!data){
            return false;
        }
        for (var i = 0; i < data.length; i++) {
            if(data[i].pointId === id){
                return true;
            }
        }
        return false;
    }
    var checkboxClicked = false; // 是否点击选择过checkbox

    table.on('checkbox(pointTable)',function (obj) {
        if(obj.type === "one"){ //单选操作
            if (obj.checked == true){
                checkboxClicked = true;
                var flag = hasTheData(pointItems,obj.data.pointId);
                // pointItems[i] = obj.data;
                i++;
                if(!flag){
                    pointItems.push(obj.data);
                }
            }else {
                if(checkboxClicked){
                    deleteById(obj.data.pointId);
                }
            }
        }
        pointItems = pointItems.filter(function (value) {
            return value && value.toString().trim();
        });
    });

    $("#addPoint").on('click',function () {
        if(table.checkStatus('pointTable').isAll){
            table.reload('pointList',{
                data: table.checkStatus('pointTable').data
            },'data');
            console.log(table.checkStatus('pointTable').data)
            layer.close(index);
        }else{
            table.reload('pointList',{
                data: pointItems
            },'data');
            layer.close(index);
        }
    });

    //移除点位
    table.on('tool(pointList)',function (obj) {
        if (obj.event === 'deletePoint'){
            var flag = hasTheData(deletePointId,obj.data.pointId);
            //记录被移除的点位信息
            if(!flag){
                deletePointId.push(obj.data.pointId);
                deleteById(obj.data.pointId);
            }
            // deletePointId[b] = obj.data.pointId;
            b++;
            obj.del();
        }
    });

    function deleteById(id){
        for (var j=0; j < pointItems.length; j++){
            if(pointItems[j] != null && pointItems[j].pointId === id){
                pointItems.splice(j,1);
            }
        }
    }

    form.on("submit(addBtn)",function (data) {
        layer.confirm('是否确认提交？',{btn: ['确定','返回']},function (index) {
            var dataArray = pointListData.data;
            var dataArrayJson = JSON.stringify(dataArray);
            var deletePointIdJson = JSON.stringify(deletePointId);
            $.ajax({
                url: baseUrl+"/eleinspect/line/saveLineInfo",
                type: 'post',
                data: {
                    lineId: $("#lineId").val(),
                    lineName: $("#lineName").val(),
                    lineInspectTime: $("#lineInspectTime").val(),
                    lineInspectErrorTime: $("#lineInspectErrorTime").val(),
                    deletePointIdJson: deletePointIdJson,
                    dataArrayJson: dataArrayJson,
                    editIndex: editIndex
                },
                success:function(data){
                    if (data.code == 0) {
                        layer.closeAll();
                        layer.alert(data.msg,{icon:1});
                        //执行重载
                        table.reload('lineTable', {});
                    }else{
                        layer.alert(data.msg,{icon:2});
                        table.reload('pointList', {});
                    }
                }
            });
        });
        return false;
    });

    form.on('submit(search)',function (data) {
        var lineId = $('#lineNumber').val();
        var searchText = $('#searchText').val();
        table.reload('lineTable', {
            page: {curr: 1},
            where: {
                lineId:lineId,lineName: searchText.trim(),
            }
        }, 'data');
        return false;
    });

    active = {
        reload: function(){
            //执行重载
            table.reload('lineTable', {

            });
        }
    }

});

function reload(){
    $("#lineNumber").val("");//火狐需要
    $("#searchText").val("");//火狐需要
    location.reload();
}